package com.train.mgr.modules.biz.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.fastjson2.JSONObject;
import com.train.mgr.modules.biz.service.IAliQwenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Slf4j
@RequiredArgsConstructor
@Service("IAliQwenService")
public class AliQwenServiceImpl implements IAliQwenService {

    @Value("${aliyun.qwen.apiModel}")
    private String qwenModel;

    @Value("${aliyun.qwen.apiKey}")
    private String qwenApiKey;


    /** 传入任意提示词，返回模型完整回答 */
    public String getQwenFeedBack(String prompt) {
        try {
            // 1. 构造消息列表（支持多轮，这里单轮）
            Message systemMsg = Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content("You are a helpful assistant.")
                    .build();
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(prompt)
                    .build();

            // 2. 组装参数
            GenerationParam param = GenerationParam.builder()
                    .apiKey(qwenApiKey) // 环境变量读取
                    .model(qwenModel)                         // 指定模型
                    .messages(Arrays.asList(systemMsg, userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();

            // 3. 同步调用
            GenerationResult result = new Generation().call(param);
           // log.info("同步调用通义千问接口返回结果 {}",JSONObject.toJSONString(result));
            // 4. 提取回复内容
            return result.getOutput().getChoices().get(0).getMessage().getContent();
        }catch (Exception ex){
            log.error("error:{}",ex);
            return "";
        }
    }

}
